<?php

namespace app\api\service\event;

use app\api\model\event\Event;
use app\api\model\event\Material;
use app\api\model\event\Merchant;
use app\api\model\event\MerchantLog;
use app\api\model\event\Order;
use app\api\model\event\Video;
use app\api\model\event\PlatformValue;
use app\api\model\event\Product;
use app\api\service\token\LoginToken;
use app\lib\exception\event\MerchantException;
use LinCmsTp5\admin\model\LinUser;
use think\Db;
use think\Exception;

class MerchantService
{
    private static $instance;


    public static function getInstance(): MerchantService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;

    }


    /**
     * @param $params
     * @throws MerchantException
     */
    public function merchantRegister($params){
        $merchant = Merchant::where("phone",$params['phone'])->findOrEmpty();
        if (!$merchant->isEmpty()){
            throw new MerchantException([
                'msg' => '手机号已注册',
                'error_code' => 20001
            ]);
        }
        $user = LinUser::where('username',$params['account'])->find();
        if ($user) {
            throw new MerchantException([
                'msg' => '账号已存在，请重新输入',
                'error_code' => 20002
            ]);
        }
        $merchant = Merchant::where("account",$params['account'])->findOrEmpty();
        if (!$merchant->isEmpty()){
            throw new MerchantException([
                'msg' => '账号已存在，请重新输入',
                'error_code' => 20002
            ]);
        }
        DB::startTrans();
        try {
            $merchant = Merchant::create($params);
            $feishu = [
                "text"=>"fs平台商户注册通知接收 : ".$params['phone']."\n公司名 : ".$params['company']."\n内容 : 商户注册"."\n注册时间 : ".$merchant['create_time']
            ];
            $this->feishu($feishu);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new MerchantException([
                'msg' => '商户注册失败',
                'error_code' => 20002
            ]);
        }
        return true;

    }

    /**
     * @throws MerchantException
     */
    public function merchantInfo(){
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $merchant = Merchant::field("company,phone,recommend,license,balance")->where("uid",$uid)->find();
        return $merchant;
    }


    /**
     * @param $params
     * @throws MerchantException
     */
    public function getMerchantProduct($params){
        $pageSize = $params['pageSize']??50;
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $gid = $login->getCurrentGid();
        $product = Product::field('id,title,SKU,url,cover,status,type,create_time');
        if ($uid != 1 && $gid !=2) {
            $merchant_id = Merchant::where("uid",$uid)->value("id");
            $product->where("merchant_id",$merchant_id);
        }

        $list = $product->paginate($pageSize);
        return $list;

    }


    /**
     * @param $params
     * @throws MerchantException
     */
    public function createMerchantProduct($params){
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $merchant_id = Merchant::where("uid",$uid)->value("id");


        DB::startTrans();
        try {
            $data = [
                "merchant_id"=>$merchant_id,
                "title"=>$params['title'],
                "url"=>$params['url'],
                "cover"=>$params['cover']??null,
                "status"=>1,
                "type"=>$params['type']??null
            ];
            Product::create($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new MerchantException([
                'msg' => '商品创建失败',
                'error_code' => 20002
            ]);
        }
    }

    /**
     * @param $params
     * @throws MerchantException
     */
    public function updateMerchantProduct($params){
        $product = Product::where("id",$params['id'])->findOrEmpty();
        if ($product->isEmpty()){
            throw new MerchantException([
                'msg' => '商品不存在',
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            $product->save($params);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new MerchantException([
                'msg' => '商品编辑失败',
                'error_code' => 20002
            ]);
        }
    }


    /**
     * @param $params
     * @throws MerchantException
     */
    public function getMerchantOrder($params){
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $gid = $login->getCurrentGid();
        $pageSize = $params['pageSize']??50;
        $order = Order::field("*")->json(['material_ids','data'])->with(['product','t_num','v_num']);
        if ($uid != 1 && $gid !=2){
            $merchant_id = Merchant::where("uid",$uid)->value("id");
            $order->where("merchant_id",$merchant_id);
        }

        $list = $order->order("id desc")->paginate($pageSize)->each(function($item){
            # 总篇数
            $total_num = 0;
            # 图文总篇数
            $text_num = 0;
            # 视频总篇数
            $video_num = 0;
            foreach ($item->data as $v){
                $arr = (array)$v;
                $total_num+=$arr['num'];
                if ($arr['type'] == 1){
                    $text_num+=$arr['num'];
                }
                if ($arr['type'] == 2){
                    $video_num+=$arr['num'];
                }
            }
            $item->total_num = $total_num;
            $item->text_num = $text_num;
            $item->video_num = $video_num;
            # 已完成
            $item->complete_total_num = count($item->t_num) + count($item->v_num);
            $item->complete_text_num = count($item->t_num);
            $item->complete_video_num = count($item->v_num);
            # 单独平台已写篇数
            $cr = CreatorService::getInstance();
            $platform_arr = $cr->platformArr($item->id);
            $item->platform_text = $platform_arr[0];
            $item->platform_video = $platform_arr[1];
            # 单独平台已分发成功数
            $complete_arr = $cr->platformArr($item->id,2);
            $item->complete_text = $platform_arr[0];
            $item->complete_video = $platform_arr[1];
            unset($item->t_num);
            unset($item->v_num);
            unset($platform_arr);
            unset($complete_arr);

        });
        return $list;
    }




    /**
     * @param $params
     * @throws MerchantException
     */
    public function createMerchantOrder($params){
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
//        $product = Product::where("id",$params['product_id'])->where("status",1)->findOrEmpty();
//        if ($product->isEmpty()){
//            throw new MerchantException([
//                'msg' => '商品未通过审核',
//                'error_code' => 20001
//            ]);
//        }
        $platform = PlatformValue::field("*")->select()->toArray();
        $merchant = Merchant::where("uid",$uid)->findOrEmpty();
        if ($merchant->isEmpty()){
            throw new MerchantException([
                'msg' => '商户不存在',
                'error_code' => 20002
            ]);
        }
        $is_material = 1;
        # 判断是否有素材
        if (empty($params['material_ids'])){
            $is_material = 2;
        }

        #计算扣除火箭豆
        $value = 0;
        foreach ($params['data'] as $v){
            foreach ($platform as $k){
                if ($v['name'] == $k['name'] && $v['num'] > 0){
                    if ($is_material == 1){
                        if ($v['type'] == 1){
                            $value += $k['text_value'] * $v['num'];
                        }else{
                            $value += $k['video_value'] * $v['num'];
                        }
                        break;
                    }else{
                        if ($v['type'] == 1){
                            $value += $k['ther_text_value'] * $v['num'];
                        }else{
                            $value += $k['ther_video_value'] * $v['num'];
                        }
                        break;
                    }
                }
            }
        }

        if ($merchant['balance']<$value){
            throw new MerchantException([
                'msg' => '火箭豆不足抵扣',
                'error_code' => 20003
            ]);
        }

        DB::startTrans();
        try {
            # 添加订单
            $params['merchant_id'] = $merchant['id'];
            $params['material_type'] = $is_material;
            $order = Order::create($params);
            # 扣除账户
            $merchant->setDec("balance",$value);
            $log = [
                "merchant_id"=>$merchant['id'],
                "balance"=>$value,
                "order_id"=>$order['id'],
                "content"=>"下单扣除火箭豆",
                "type"=>2
            ];
            MerchantLog::create($log);

            $feishu = [
                "text"=>"fs平台商户下单通知接收 : "."\n"."内容 : 商户商户"."\n下单时间 : ".$order['create_time']
            ];
            $this->feishu($feishu);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new MerchantException([
                'msg' => '创建商户订单失败',
                'error_code' => 20004
            ]);
        }
    }

    /**
     * @param $params
     * @throws MerchantException
     */
    public function updateMerchantOrder($params){
        $order = Order::where("id",$params['id'])->findOrEmpty();
        if ($order->isEmpty()){
            throw new MerchantException([
                'msg' => '订单不存在',
                'error_code' => 20001
            ]);
        }
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
//        $product = Product::where("id",$params['product_id'])->where("status",1)->findOrEmpty();
//        if ($product->isEmpty()){
//            throw new MerchantException([
//                'msg' => '商品未通过审核',
//                'error_code' => 20001
//            ]);
//        }
        $platform = PlatformValue::field("*")->select()->toArray();
        $merchant = Merchant::where("uid",$uid)->findOrEmpty();
        if ($merchant->isEmpty()){
            throw new MerchantException([
                'msg' => '商户不存在',
                'error_code' => 20002
            ]);
        }

        $is_material = 1;
        # 判断是否有素材
        if (empty($params['material_ids'])){
            $is_material = 2;
        }

        #计算扣除火箭豆
        $value = 0;
        foreach ($params['data'] as $v){
            foreach ($platform as $k){
                if ($v['name'] == $k['name'] && $v['num'] > 0){
                    if ($is_material == 1){
                        if ($v['type'] == 1){
                            $value += $k['text_value'] * $v['num'];
                        }else{
                            $value += $k['video_value'] * $v['num'];
                        }
                        break;
                    }else{
                        if ($v['type'] == 1){
                            $value += $k['ther_text_value'] * $v['num'];
                        }else{
                            $value += $k['ther_video_value'] * $v['num'];
                        }
                        break;
                    }
                }
            }
        }

        if ($merchant['balance']<$value){
            throw new MerchantException([
                'msg' => '火箭豆不足抵扣',
                'error_code' => 20003
            ]);
        }

        DB::startTrans();
        try {
            # 编辑订单
            $params['material_type'] = $is_material;
            $order->save($params);
            # 扣除账户
            $merchant->setDec("balance",$value);
            $log = [
                "merchant_id"=>$merchant['id'],
                "balance"=>$value,
                "order_id"=>$order['id'],
                "content"=>"下单扣除火箭豆",
                "type"=>2
            ];
            MerchantLog::create($log);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new MerchantException([
                'msg' => '商户订单编辑成功',
                'error_code' => 20004
            ]);
        }
    }

    /**
     * @param $params
     * @throws MerchantException
     */
    public function getMerchantMaterial($params){
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $gid = $login->getCurrentGid();
        $pageSize = $params['pageSize']??50;
        $material = Material::field("*");
        if ($uid != 1 && $gid !=2 && $gid!=3){
            $merchant_id = Merchant::where("uid",$uid)->value("id");
            $material->where("merchant_id",$merchant_id);
        }
        if (!empty($params['product_id'])){
            $material->where("product_id",$params['product_id']);
        }

        if (!empty($params['order_id'])){
            $order = Order::field('material_ids')->json(['material_ids'])->where("id",$params['order_id'])->find();
            if ($order){
                $material->where("num","<",1)->whereIn("id",$order['material_ids']);
            }
        }

        if (!empty($params['type'])){
            $material->where("type",$params['type']);
        }

        $list = $material->order("id desc")->paginate($pageSize);
        return $list;

    }

    /**
     * @param $params
     * @throws MerchantException
     */
    public function createMerchantMaterial($params){
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $product = Product::where("id",$params['product_id'])->where("status",1)->findOrEmpty();
        if ($product->isEmpty()){
            throw new MerchantException([
                'msg' => '商品不存在',
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            $merchant_id = Merchant::where("uid",$uid)->value("id");
            foreach ($params['materials'] as $v){
                $data = [
                    "merchant_id"=>$merchant_id,
                    "product_id"=>$params['product_id'],
                    "url"=>$v['url'],
                    "type"=>$v['type']
                ];
                Material::create($data);
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new MerchantException([
                'msg' => '素材添加失败',
                'error_code' => 20002
            ]);
        }
    }


    /**
     * @param $params
     * @throws MerchantException
     */
    public function deleteMerchantMaterial($id){
        $material = Material::where("id",$id)->findOrEmpty();
        if ($material->isEmpty()){
            throw new MerchantException([
                'msg' => '素材不存在',
                'error_code' => 20001
            ]);
        }

        DB::startTrans();
        try {
            $material->delete();
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new MerchantException([
                'msg' => '素材删除失败',
                'error_code' => 20002
            ]);
        }

    }

    /**
     * @param $params
     * @throws MerchantException
     */
    public function getPropertyLog($params){
        $pageSize = $params['pageSize']??50;
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $gid = $login->getCurrentGid();
        $log = MerchantLog::field("*");
        if ($uid!=1 && $gid !=2){
            $merchant = Merchant::where("uid",$uid)->find();
            $log->where("merchant_id",$merchant['id']??0);
        }
        $list = $log->paginate($pageSize);
        return $list;
    }


    /**
     * @param $params
     * @throws MerchantException
     */
    public function getDataAnalysis($params){
        $pageSize = $params['pageSize']??50;
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $gid = $login->getCurrentGid();
        $event = Event::field('title,app_id,feed_id,content_id,source_platform,platform,view,like,reply,coin,favorite,share')
        ->where("status",3);
        $merchant = "";
        if ($uid!=1 && $gid !=2){
            $merchant = Merchant::where("uid",$uid)->find();
            $event->where("merchant_id",$merchant['id']);
        }
        if (isset($params['source_platform'])){
            if ($params['source_platform'] != '') {
                $event->where("source_platform", $params['source_platform']);
            }
        }
        $list = $event->order("id desc")->paginate($pageSize);
        $data = ["list"=>$list];
        $data['Explosive'] = ["a"=>0,"s"=>0,"b"=>0,"proportion"=>0];
        #最高评论量
        $view_query = Event::field("title,content,images,get_time,url,view,like,reply,share")
            ->where("view",">",0)->order("view desc");
        if ($merchant != ""){
            $view_query->where("merchant_id",$merchant['id']);
        }
        $view_data = $view_query->find();
        #最高点赞量
        $like_query = Event::field("title,content,images,get_time,url,view,like,reply,share")
            ->where("like",">",0)->order("like desc");
        if ($merchant != ""){
            $like_query->where("merchant_id",$merchant['id']);
        }
        $like_data = $like_query->find();
        #最高分发量
        $reply_query = Event::field("title,content,images,get_time,url,view,like,reply,share")
            ->where("reply",">",0)->order("reply desc");
        if ($merchant != ""){
            $reply_query->where("merchant_id",$merchant['id']);
        }
        $reply_data = $reply_query->find();
        #最高阅读量
        $share_query = Event::field("title,content,images,get_time,url,view,like,reply,share")
            ->where("share",">",0)->order("share desc");
        if ($merchant != ""){
            $share_query->where("merchant_id",$merchant['id']);
        }
        $share_data = $share_query->find();
        $data['view_data'] = $view_data;
        $data['like_data'] = $like_data;
        $data['reply_data'] = $reply_data;
        $data['share_data'] = $share_data;

        #爆文分析
        $Explosive_query = Event::field("view");
        if ($merchant != ""){
            $share_query->where("merchant_id",$merchant['id']);
        }
        $Explosive = $Explosive_query->select()->toArray();
        foreach ($Explosive as $v){
            if ($v['view'] > 500 && $v['view'] <=1000){
                $data['Explosive']['b'] += 1;
            }
            elseif ($v['view'] > 1000 && $v['view'] <= 3000){
                $data['Explosive']['a'] += 1;
            }
            elseif ($v['view'] > 3000){
                $data['Explosive']['s'] += 1;
            }
        }
        $Explosive_count = count($Explosive);
        $Explosive_total = $data['Explosive']['b'] + $data['Explosive']['a'] + $data['Explosive']['s'];
        $data['Explosive']['proportion'] = round(round($Explosive_total/$Explosive_count,4) * 100,1);


        return $data;
    }

    /**
     * @param $params
     * @throws MerchantException
     */
    public function getOrderAnalysis($params){
        $list = Event::field("sum(`view`) as views,sum(`like`) as likes,sum(reply) as replys,sum(`share`) as shares")
            ->where("order_id",$params['order_id'])->group("order_id")->select()->toArray();
        $data = $list[0]??["views"=>0,"likes"=>0,"replys"=>0,"shares"=>0];
        #最高评论量
        $view_data = Event::field("title,content,images,get_time,url,view,like,reply,share")
        ->where("view",">",0)->order("view desc")->where("order_id",$params['order_id'])->find();
        #最高点赞量
        $like_data = Event::field("title,content,images,get_time,url,view,like,reply,share")
        ->where("like",">",0)->order("like desc")->where("order_id",$params['order_id'])->find();
        #最高分发量
        $reply_data = Event::field("title,content,images,get_time,url,view,like,reply,share")
        ->where("reply",">",0)->order("reply desc")->where("order_id",$params['order_id'])->find();
        #最高阅读量
        $share_data = Event::field("title,content,images,get_time,url,view,like,reply,share")
        ->where("share",">",0)->order("share desc")->where("order_id",$params['order_id'])->find();
        $data['view_data'] = $view_data;
        $data['like_data'] = $like_data;
        $data['reply_data'] = $reply_data;
        $data['share_data'] = $share_data;
        $data['Explosive'] = ["a"=>0,"s"=>0,"b"=>0,"proportion"=>0];
        #爆文分析
        $Explosive = Event::field("view")
            ->where("order_id",$params['order_id'])->select()->toArray();
        foreach ($Explosive as $v){
            if ($v['view'] > 500 && $v['view'] <=1000){
                $data['Explosive']['b'] += 1;
            }
            elseif ($v['view'] > 1000 && $v['view'] <= 3000){
                $data['Explosive']['a'] += 1;
            }
            elseif ($v['view'] > 3000){
                $data['Explosive']['s'] += 1;
            }
        }
        $Explosive_count = count($Explosive);
        $Explosive_total = $data['Explosive']['b'] + $data['Explosive']['a'] + $data['Explosive']['s'];
        if ($Explosive_total !=0){
            $data['Explosive']['proportion'] = round(round($Explosive_total/$Explosive_count,4) * 100,1);
        }else{
            $data['Explosive']['proportion'] = 0;
        }


        return $data;

    }



    # 飞书通知
    public function feishu($params){
        try {
            $url = "https://open.feishu.cn/open-apis/bot/v2/hook/9b772e7b-ccf4-41e2-939c-4bb702d86e5f";

            $data = [
                "msg_type"=>"text",
                "content"=>[
                    "text"=>$params['text']
                ]
            ];

            $this->_post($url,$data);
        }catch (Exception $e){
//            throw new DictException(["msg" => $e->getMessage()]);
        }
    }


    public function _post($url,$data){
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);

    }
}
